package com.codingfly.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class ServiceConfig {
    @Resource
    private NacosDiscoveryProperties discoveryProperties;
    @Resource
    private NacosServiceDiscovery serviceDiscovery;
    @Resource
    private ServiceEventListener eventListener;
    private volatile NamingService naming;
    protected static volatile List<String> services = new ArrayList<>();
    protected volatile long time = 30000;

    @Autowired
    public void init() {
        try {
            naming = discoveryProperties.namingServiceInstance();
            services = serviceDiscovery.getServices();
            services.forEach(this::addServiceListener);

            new Thread(()-> {
                for (;;) {
                    try {
                        Thread.sleep(time);
                        List<String> newServices = serviceDiscovery.getServices();
                        for (String service : newServices) {
                            if (!services.contains(service)) {
                                services.add(service);
                                addServiceListener(service);
                            }
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();

        } catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 新的服务添加监听
     * @param serviceName
     */
    public void addServiceListener(String serviceName){
        try {
            naming.subscribe(serviceName, eventListener);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
